%%
clearvars
close all

filePath = matlab.desktop.editor.getActiveFilename;
fprintf('%s\n',filePath);

repository_base = fileparts(fileparts(filePath));
addpath(fullfile(repository_base, "scripts"));
addpath(fullfile(repository_base, "scripts", "libs"));

run(fullfile(repository_base, "scripts", "libs", "eeglab", "eeglab.m"))

session_list{1} = 'sub-A';
session_list{2} = 'sub-B';
session_list{3} = 'sub-C';
session_list{4} = 'sub-D';
session_list{5} = 'sub-E';
session_list{6} = 'sub-F';
session_list{7} = 'sub-G';
session_list{8} = 'sub-H';
session_list{9} = 'sub-I';
session_list{10} = 'sub-J';
session_list{11} = 'sub-K';

f_base = fullfile(repository_base, 'epochs');
save_base = fullfile(repository_base, 'results');

for session_idx = 1:length(session_list)
    session = session_list{session_idx}
    f_name = fullfile(f_base, strcat(session, '_filt_2_0.1_40.mat'));
    load(f_name);
    epochs_{session_idx} = epochs;
end

epochs = epochs_;

eeg_ch = 1:64;
eeg_th = [-100 100];

eog_ch = 65:66;
eog_th = [-500 500];

ch_idx = 32;

for session_idx = 1:8
    for idx_att = 1:3
        for idx_marker = 1:3
            epochs{session_idx}.att{idx_att}.marker{idx_marker}.rej_th(eeg_ch, eeg_th);
            epochs{session_idx}.att{idx_att}.marker{idx_marker}.rej_th(eog_ch, eog_th);
        end
    end
end

%%
for idx_att = 1:3
    for idx_marker = 1:3
        data.att{idx_att}.marker{idx_marker} = [];
    end
end

for session_idx = 1:8
    for idx_att = 1:3
        for idx_marker = 1:3
            data.att{idx_att}.marker{idx_marker} = cat(3, data.att{idx_att}.marker{idx_marker}, epochs{session_idx}.att{idx_att}.marker{idx_marker}.data);
        end
    end
end

%%
time = epochs{1}.att{1}.marker{1}.time;
size(data.att{1}.marker{1})
size(mean(data.att{1}.marker{1},3))

time_slices = {[0.15 0.3], [0.25], [0.25]};
devs = [1 2 3];

for idx_dev = 1:length(devs)
    dev = devs(idx_dev);
    for idx_time_slice = 1:length(time_slices{idx_dev})
        time_slice = time_slices{idx_dev}(idx_time_slice);
        [~, I] = min(abs(time - time_slice));
        f = figure();
        for att = 1:3
            evo = mean(data.att{att}.marker{dev}(1:64,:,:), 3);
            subplot(1,3,att)
            topoplot(evo(:,I), '64ch.ced', 'maplimits', [-6 6], 'electrodes', 'on', 'whitebk', 'on');
        end
        set(gcf,'color','w');
        fig = gcf;
        fig.Position = [480, 480, 1600, 400];
        
        exportgraphics(f, fullfile(save_base, strcat('grand_topo_responses_to_',num2str(dev), '_(', num2str(time_slice),'s).png')), 'resolution', 300)
    end
end